using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using System.IO;
using System;

/*
 * 导出工程
 * 
 * 安卓包上传到后台后，记得把build.gradle里的版本号+1提交,备份好Buyly mapping文件
 */

public static class BuildProject
{

    private static string _tempBuildFolderName = "TempBuild";

    [MenuItem("Tools/打包")]
    public static void BuildAndroidProject()
    {
        // 解析命令行参数
        string[] args = System.Environment.GetCommandLineArgs();
        foreach (var s in args)
        {
            if (s.Contains("--productName:"))
            {
                string productName = s.Split(':')[1];
                // 设置app名字
                PlayerSettings.productName = productName;
            }

            if (s.Contains("--version:"))
            {
                string version = s.Split(':')[1];
                // 设置版本号
                PlayerSettings.bundleVersion = version;
            }
        }

        string outPutPath = Path.Combine(GetProjectPath(), _tempBuildFolderName);
        // 切换Split Application Binary状态
        AssetDatabase.SaveAssets();
        Debug.Log("OutputPath :" + outPutPath);
        Time.timeScale = 1;
        Application.targetFrameRate = 30;
        BuildProjectAndroidStudio(outPutPath);
    }

    static List<string> GetSceneName()
    {
        List<string> sceneNames = new List<string>();
        foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes)
            if (scene.enabled)
                sceneNames.Add(scene.path);
        return sceneNames;
    }

    public static void BuildProjectAndroidStudio(string exportDirPath)
    {
        if (!Directory.Exists(exportDirPath))
            Directory.CreateDirectory(exportDirPath);

        // 清除资源目录
        var srcPath = Path.Combine(exportDirPath, "unityLibrary/src/main");
        if (Directory.Exists(srcPath))
        {
            Directory.Delete(srcPath, true);
        }

        if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android)
            EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Android, BuildTarget.Android);
        EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
        EditorUserBuildSettings.exportAsGoogleAndroidProject = true;
        EditorUserBuildSettings.buildAppBundle = false;

        //EditorUserBuildSettings.development = true;
        //EditorUserBuildSettings.connectProfiler = true;
        //EditorUserBuildSettings.buildWithDeepProfilingSupport = true;

        PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARM64 | AndroidArchitecture.ARMv7;
        List<string> sceneNames = GetSceneName();
        BuildPipeline.BuildPlayer(sceneNames.ToArray(), exportDirPath, BuildTarget.Android, BuildOptions.AcceptExternalModificationsToPlayer);
    }

    public static void BuildProjectXcode(string exportDirPath)
    {
        if (!Directory.Exists(exportDirPath))
            Directory.CreateDirectory(exportDirPath);

        if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.iOS)
            EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.iOS, BuildTarget.iOS);
        PlayerSettings.SetScriptingBackend(BuildTargetGroup.iOS, ScriptingImplementation.IL2CPP);
        List<string> sceneNames = GetSceneName();
        BuildPipeline.BuildPlayer(sceneNames.ToArray(), exportDirPath, BuildTarget.iOS, BuildOptions.None);
    }

    public static void CopyDirectory(string from, string to)
    {
        if (!Directory.Exists(from)) return;

        if (!Directory.Exists(to))
            Directory.CreateDirectory(to);

        List<string> files = new List<string>(Directory.GetFiles(from));
        files.ForEach(c =>
        {
            string destFile = Path.Combine(new string[] { to, Path.GetFileName(c) });
            File.Copy(c, destFile, true);
        });
        List<string> folders = new List<string>(Directory.GetDirectories(from));
        folders.ForEach(c =>
        {
            string destDir = Path.Combine(new string[] { to, Path.GetFileName(c) });
            CopyDirectory(c, destDir);
        });
    }

    public static string GetProjectPath()
    {
        return Application.dataPath.Remove(Application.dataPath.Length - 7);
    }

    public static string GetFullProjectPath()
    {
        return Path.Combine(GetProjectPath(), _tempBuildFolderName);
    }
}
